package com.security.springmvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * name: 校验和认证配置类
 * @author yueyue
 * @Date 2025/7/18
 * @Version 1.0
 */

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 创建用户信息
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService(){
       InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
       manager.createUser(User.withUsername("admin").password("admin").roles("ADMIN").build());
       manager.createUser(User.withUsername("user123").password("123456").roles("USER").build());
       return manager;
    }

    /**
     * 密码编码器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 配置权限
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/r/r1").hasRole("ADMIN") // 访问/r/r1 需要ADMIN角色
                .antMatchers("/r/r2").hasRole("user") // 访问/r/r2 需要user角色
                .antMatchers("/r/**").authenticated() // 访问/r/** 需要认证
                .anyRequest().permitAll() // 其他请求全部放行
                .and()
                .formLogin() // 开启表单登录
                .successForwardUrl("/login-success");// 登录成功跳转路径
    }

}
